package pl.koziolekweb.dbunter;

import static pl.koziolekweb.dbunter.DBLoader.table;

import java.io.Reader;

import org.dbunit.dataset.AbstractDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.DefaultTableIterator;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.ITableIterator;
import org.dbunit.dataset.OrderedTableNameMap;

import com.google.gson.Gson;

public class JsonDataSet extends AbstractDataSet {

	private class JsonTable {
		private String[] columns;
		private String name;
		private String[][] rows;

		public String[] columns() {
			return columns;
		}

		public String name() {
			return name;
		}

		public String[][] rows() {
			return rows;
		}

	}

	private final OrderedTableNameMap _tables;

	private JsonTable[] tables;

	private JsonDataSet() {
		_tables = super.createTableNameMap();
	}

	@Override
	protected ITableIterator createIterator(boolean reversed)
			throws DataSetException {
		@SuppressWarnings("unchecked")
		ITable[] tables = (ITable[]) _tables.orderedValues().toArray(
				new ITable[0]);
		return new DefaultTableIterator(tables, reversed);
	}

	private JsonDataSet init() throws DataSetException {
		for (JsonTable jsonTable : tables) {
			ITable iTable = table(jsonTable.name(), jsonTable.columns(),
					jsonTable.rows());
			_tables.add(iTable.getTableMetaData().getTableName(), iTable);
		}
		return this;
	}

	public static JsonDataSet build(Reader jsonReader) throws DataSetException {
		JsonDataSet fromJson = new Gson().fromJson(jsonReader,
				JsonDataSet.class);
		return fromJson.init();
	}

	public static JsonDataSet build(String jsonString) throws DataSetException {
		final JsonDataSet fromJson = new Gson().fromJson(jsonString,
				JsonDataSet.class);
		return fromJson.init();
	}
}